from django.db import models

from polls.utils import to_md5_hex


class Subject(models.Model):
    """学科（模型类）"""

    no = models.AutoField(primary_key=True, verbose_name='编号')
    name = models.CharField(max_length=20, verbose_name='名称')
    intro = models.CharField(max_length=1000, verbose_name='介绍')
    is_hot = models.BooleanField(default=False, verbose_name='是否热门')

    def __str__(self):
        return f'{self.no}: {self.name}'

    class Meta:
        db_table = 'tb_subject'
        verbose_name = '学科'
        verbose_name_plural = '学科'


class Teacher(models.Model):
    """老师（模型类）"""

    no = models.IntegerField(primary_key=True, verbose_name='工号')
    name = models.CharField(max_length=20, verbose_name='姓名')
    sex = models.BooleanField(default=True, verbose_name='性别')
    birth = models.DateField(verbose_name='出生日期')
    photo = models.ImageField(upload_to='images', default='', max_length=512, verbose_name='头像')
    intro = models.CharField(default='', max_length=1000, verbose_name='介绍')
    good_count = models.IntegerField(default=0, verbose_name='好评数')
    bad_count = models.IntegerField(default=0, verbose_name='差评数')
    subject = models.ForeignKey(to=Subject, on_delete=models.PROTECT, db_column='sno', verbose_name='所属学科')

    def __str__(self):
        return f'{self.no}: {self.name}'

    class Meta:
        db_table = 'tb_teacher'
        verbose_name = '老师'
        verbose_name_plural = '老师'


class User(models.Model):
    """用户（模型类）"""

    no = models.AutoField(primary_key=True, verbose_name='编号')
    username = models.CharField(max_length=20, unique=True, verbose_name='用户名')
    password = models.CharField(max_length=32, verbose_name='口令')
    email = models.CharField(default='', max_length=256, verbose_name='邮箱')
    tel = models.CharField(max_length=11, verbose_name='手机号')
    reg_date = models.DateTimeField(auto_now_add=True, verbose_name='注册日期')
    last_visit = models.DateTimeField(verbose_name='最后访问')

    def save(self):
        # 商业代码中还需要对用户口令进行加盐操作
        self.password = to_md5_hex(self.password)
        super().save()

    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户'
        verbose_name_plural = '用户'

